package com.help.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.ObjectUtil;
import com.github.javafaker.Address;
import com.github.javafaker.Faker;
import com.help.common.api.CommonResult;
import com.help.common.exception.Asserts;
import com.help.common.util.JwtUtil;
import com.help.config.WxMaConfiguration;
import com.help.domain.HelpNote;
import com.help.domain.User;
import com.help.domain.UserLoginPojo;
import com.help.domain.fakeAddr;
import com.help.service.UserService;
import com.help.service.impl.HelpNoteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;


@Api(tags = "用户相关接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private HelpNoteService helpNoteService;

    @Value("${wxappid}")
    private String appid;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public CommonResult login(@RequestBody UserLoginPojo userLoginPojo){
        if (StringUtils.isEmpty(userLoginPojo.getJsCode())){
            Asserts.fail("用户jsCode不能为空！");
        }
        WxMaJscode2SessionResult sessionInfo = null;
        try {
            WxMaService maService = WxMaConfiguration.getMaService(appid);
            WxMaUserService userMaService = maService.getUserService();
            sessionInfo = userMaService.getSessionInfo(userLoginPojo.getJsCode());
        } catch (WxErrorException e) {
            Asserts.fail("用户jsCode无效！");
        }
        String openid = sessionInfo.getOpenid();
        User user = userService.lambdaQuery().eq(User::getOpenid, openid).one();
        //如果用户未注册过
        if (ObjectUtil.isNull(user)){
            //直接注册一个新的用户
            user = new User();
            user.setOpenid(openid);
            user.setNickName(userLoginPojo.getNickName()!=null?userLoginPojo.getNickName():null);
            user.setAvatarUrl(userLoginPojo.getUserAvatarUrl()!=null?userLoginPojo.getUserAvatarUrl():null);
            userService.save(user);
        }else{
            //更新信息
            user.setAvatarUrl(userLoginPojo.getUserAvatarUrl()!=null?userLoginPojo.getUserAvatarUrl():null);
            user.setNickName(userLoginPojo.getNickName()!=null?userLoginPojo.getNickName():null);
            userService.updateById(user);
        }
        //生成token
        String token = JwtUtil.getToken(user);
        return CommonResult.success(token,"登录成功！");
    }

    @ApiOperation("个人发布")
    @GetMapping("/myHelp")
    public CommonResult myHelp(@RequestHeader("token") String token){
        Map<String, Object> userMap = JwtUtil.getUserMap(token);
        List<HelpNote> list = helpNoteService.lambdaQuery().eq(HelpNote::getOpenid, userMap.get("openid")).list();
        return CommonResult.success(list);
    }


    @ApiOperation("验证token是否有效")
    @GetMapping("/tokenCheck")
    public CommonResult isToken(@RequestHeader("token") String token) {
        //配置拦截器，让拦截器去判断token去，前端要一个接口用用
        return CommonResult.success("success");
    }

    @ApiOperation("获取用户详细信息")
    @GetMapping("/getUserInfo")
    public CommonResult getUserInfo(@RequestHeader("token") String token) {
        String openid = JwtUtil.getOpenid(token);
        User user = userService.lambdaQuery().eq(User::getOpenid, openid).one();
        return CommonResult.success(user);
    }

    @ApiOperation("假地区生成")
    @GetMapping("/fakeAddr")
    public CommonResult getAddress(@RequestHeader("token") String token) {
        Faker faker = new Faker(new Locale("zh-CN"));
        Address address = faker.address();

        List<fakeAddr> list = new ArrayList<>();

        for (int i = 0; i < 50; i++) {
            fakeAddr fakeAddr = new fakeAddr();
            fakeAddr.setCity(address.cityName() + '市');
            fakeAddr.setArea(address.streetName() + '区');
            fakeAddr.setStreet(address.streetAddress());
            list.add(fakeAddr);
        }
        return CommonResult.success(list);
    }
}
